//
//  JHSSicknessManageController.m
//  病例管理
//
//  Created by chenWei on 2017/3/24.
//  Copyright © 2017年 陈伟. All rights reserved.
//

#import "JHSSicknessManageController.h"
#import "JHSSicknessTypeChooseController.h"
#import "JHSSicknessDevideController.h"
#import "JHSSickDevideModel.h"
#import "JHSSickDesprationController.h"
#import "JHSSicknessModel.h"
#import <HMImagePickerController.h>


@interface JHSSicknessManageController ()<JHSSicknessTypeChooseControllerDelegate,JHSSicknessDevideControllerDelegate,JHSSickDesprationControllerDelegate,HMImagePickerControllerDelegate>

//病例行数
@property (nonatomic, assign) NSInteger sickCount;

//保存模型数据
@property (nonatomic, strong) NSMutableArray *modelArr;

//接收管理病例类型控制器传过来的数据
@property (nonatomic, strong) NSMutableDictionary *dic;


@property (strong, nonatomic) IBOutlet UIImageView *addImageView;

//装着 lab 的背景图片
@property (weak, nonatomic) IBOutlet UIView *zeroView;

@property (weak, nonatomic) IBOutlet UIView *firstView;

@property (weak, nonatomic) IBOutlet UIView *secondView;

@property (weak, nonatomic) IBOutlet UIView *threeView;

@property (weak, nonatomic) IBOutlet UIView *fourView;

@property (weak, nonatomic) IBOutlet UIView *fiveView;

@property (weak, nonatomic) IBOutlet UIView *sixView;

//显示病例症状描述的 lab
@property (weak, nonatomic) IBOutlet UILabel *zeroLab;

@property (weak, nonatomic) IBOutlet UILabel *firstLab;

@property (weak, nonatomic) IBOutlet UILabel *secondLab;

@property (weak, nonatomic) IBOutlet UILabel *threeLab;

@property (weak, nonatomic) IBOutlet UILabel *fourLab;

@property (weak, nonatomic) IBOutlet UILabel *fiveLab;

@property (weak, nonatomic) IBOutlet UILabel *sixLab;

//接收从病症描述控制器传过来的病症名数组
@property (nonatomic, strong) NSMutableArray *sickDescpNameArr;

//保存 lab 的数组
@property (nonatomic, strong) NSMutableArray *labArrM;
//保存 view 的数组
@property (nonatomic, strong) NSArray *viewArr;


@property (weak, nonatomic) IBOutlet UIButton *zeroBtn;

@property (weak, nonatomic) IBOutlet UIButton *firstBtn;

@property (weak, nonatomic) IBOutlet UIButton *secondBtn;

//占位文字
@property (weak, nonatomic) IBOutlet UILabel *placeHolderText;


//保存三个按钮
@property (nonatomic, strong) NSArray *btnArr;


// 选中照片数组
@property (nonatomic) NSMutableArray *images;
// 选中资源素材数组，用于定位已经选择的照片
@property (nonatomic) NSArray *selectedAssets;




@end

//枚举
typedef enum : NSUInteger {
    ButtonTypeZero,
    ButtonTypeFirst,
    ButtonTypeSecond,
    
} ButtonType;


@implementation JHSSicknessManageController

- (void)viewWillAppear:(BOOL)animated
{
    
    if (_labArrM == nil) {
        
        _labArrM = [NSMutableArray array];
        _viewArr = [NSArray array];
        
        //标签和视图数组
        NSArray *labArr = @[self.zeroLab,self.firstLab,self.secondLab,self.threeLab,self.fourLab,self.fiveLab,self.sixLab];
        
        NSArray *viewArr = @[self.zeroView,self.firstView,self.secondView,self.threeView,self.fourView,self.fiveView,self.sixView];
        
        //1隐藏标签
        for (UILabel *lab in labArr) {
            
            lab.hidden = YES;
        }
    
        //隐藏装着标签的视图
        for (UIView *view in viewArr) {
            
            view.hidden = YES;
        }
        
        
        //记录
        _viewArr = viewArr;
        _labArrM = (NSMutableArray *)labArr;
    }
    

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //实例化
    _modelArr = [NSMutableArray array];
    
    //实例化
    _dic = [NSMutableDictionary dictionary];
    _sickDescpNameArr = [NSMutableArray array];
    
    //实例化模型
    _sicknessModel = [[JHSSicknessModel alloc]init];
    
    //实例化模型数组
    NSMutableArray *sickManagerModelArrM = [NSMutableArray array];
    
    //实例化按钮数组
    _btnArr = [NSArray array];
    
    
    //程序启动的时候把第一个和第二个添加图片按钮隐藏
    self.firstBtn.hidden = YES;
    self.secondBtn.hidden = YES;
    
    
    NSArray *btnArr = @[self.zeroBtn,self.firstBtn,self.secondBtn];
    
    _btnArr = btnArr;
    
/*
    //创建一个图片的空数组
    _images = [NSMutableArray array];
    //创建一个PHAssets的空数组
    NSMutableArray *assets = [NSMutableArray array];
    
    //从沙盒中读取到PHAsset的identifier的数组
    NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"images"];
    NSLog(@"%@", imagePath);
    NSArray *localIdentifieArray = [NSKeyedUnarchiver unarchiveObjectWithFile:imagePath];
    
    //遍历identifier的数组, 生成PHAsset的数组
    PHFetchResult *phFetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:localIdentifieArray options: nil];
    [phFetchResult enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx,BOOL *_Nonnull stop) {
        [assets addObject: obj];
    }];
    
    _selectedAssets = assets;
    
    //遍历PHAsset的数组生成图片的数组
    for (PHAsset *asset in _selectedAssets) {
        [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(200, 200) contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable image, NSDictionary * _Nullable info) {
            [_images addObject:image];
        }];
    }
    
    //更新UI
    [self.tableView reloadData];
    
 */

    
    _sickManagerModelArrM = sickManagerModelArrM;
}

//界面已经显示的时候要来调用的方法
- (void)viewDidAppear:(BOOL)animated
{
    if (_images.count != 0) {
        
        for (NSInteger i = 0; i < _images.count; i++) {
            
            if (i == 2);
            else {
                [_btnArr[i + 1] setHidden:NO];
            }
            
            //如果图片数组中有值就取下标为0的图片传到模型 cell 中
            if (self.images.count != 0) {
                
                _sicknessModel.img = _images[0];
            }
            
            [_btnArr[i] setImage:_images[i] forState:UIControlStateNormal];
        }
    }
}


//MARK:6- 执行病症描述控制器的代理方法
- (void)sickDesprationController:(JHSSickDesprationController *)despVC andNSickDespNameArr:(NSMutableArray *)sickDespNameArr
{
    _sickDescpNameArr = sickDespNameArr;
    
    self.placeHolderText.hidden = YES;
    
    if (_sickDescpNameArr.count != 0) {
    
        for (NSInteger i = 0; i < _sickDescpNameArr.count - 1; i++) {
            
            if (_sickDescpNameArr[i] != nil && _sickDescpNameArr != nil) {
                [_labArrM[i] setText:_sickDescpNameArr[i]];
                [_labArrM[i] setHidden:NO];
                [_viewArr[i] setHidden:NO];
            }
        
        }
    }
}

//MARK:7- 使用 segue 进行跳转
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    JHSSickDesprationController *vc = (JHSSickDesprationController *)segue.destinationViewController;
    
    vc.delegate = self;
}


//MARK:3- 实现疾病类型代理方法
- (void)sicknessTypeChooseController:(JHSSicknessTypeChooseController *)sickTypeVC withNSDictionary:(NSDictionary *)dic
{
    _dic = (NSMutableDictionary *)dic;

    _typeLab.text = dic[@"name"];
    
    //把疾病类型名保存到模型中
    _sicknessModel.sickName = dic[@"name"];
    
}

//MARK:4- 实现疾病细分代理方法
- (void)sicknessDevideController:(JHSSicknessDevideController *)sickDevideVC withNSMutableArray:(NSMutableArray *)modelArr withNSIndexPath:(NSIndexPath *)index
{
    _modelArr = modelArr;
    
    _detailLab.text = modelArr[index.row][@"ci3_name"];
    
}



//MARK:1- 点击确定pop控制器到上一个控制器
- (IBAction)makeSure:(UIBarButtonItem *)sender {
    
    //把模型保存到模型数组中
    [_sickManagerModelArrM addObject:_sicknessModel];
    
    //判断代理控制器是否执行了代理方法
    if ([self.delegate respondsToSelector:@selector(sicknessManageController:withSicknessModelArrM:)]) {

        [self.delegate sicknessManageController:self withSicknessModelArrM:_sickManagerModelArrM];
    }
    
    [self.navigationController popViewControllerAnimated:YES];

}



// MARK:2- 点击删除
- (IBAction)deleteBtn:(UIBarButtonItem *)sender {
    
    NSLog(@"-=-=-=-=-=-==-      %zd",sender.tag);
    
    //当点击删除之后，要删除当前界面的数据显示，把对应的模型 cell也删除
    //先删除当前界面的数据
    //1.先删除类型 lab 的数据
    _typeLab.text = @"请选择";
    //再删除细分 lab
    _detailLab.text = @"请选择";
    
    //2.删除疾病描述的 lab
    if (_sickDescpNameArr.count != 0) {
        
        for (NSInteger i = 0; i < _sickDescpNameArr.count; i++) {
            
            if (_sickDescpNameArr[i] != nil && _sickDescpNameArr != nil) {
                [_labArrM[i] setText:@""];
                [_labArrM[i] setHidden:YES];
                [_viewArr[i] setHidden:YES];
            }
        }
    }
    
    
    
    //3.删除图片
    [self.images removeAllObjects];
    
    for (NSInteger i = 0; i < _btnArr.count; i++) {
        
        [_btnArr[i] setImage:[UIImage imageNamed:@"AddPic"] forState:UIControlStateNormal];
        
        if (i == 2);
        else {
            [_btnArr[i + 1] setHidden:YES];
        }
    }
    
    //使用通知 通知上一个模型 cell 控制器我点击了删除，然后隐藏 cell 和判断是否需要隐藏 tableView
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center postNotificationName:@"delete" object:self userInfo:nil];
    
    //出栈
    [self.navigationController popViewControllerAnimated:YES];
    
}


//MARK:3- 代理方法 跳转控制器
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //动画取消选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //疾病类型控制器
    JHSSicknessTypeChooseController *typeChooseVC = [[JHSSicknessTypeChooseController alloc]init];
    //设置代理
    typeChooseVC.delegate = self;
    
    //疾病细分控制器
    JHSSicknessDevideController *devideVC = [[JHSSicknessDevideController alloc]init];
    
    devideVC.iteger = [_dic[@"tid"] integerValue];
    
    devideVC.delegate = self;
    
    if (indexPath.row == 0) {
        
        [self.navigationController pushViewController:typeChooseVC animated:YES];
        
    }else if(indexPath.row == 1) {
        
        [self.navigationController pushViewController:devideVC animated:YES];
        
    }else if (indexPath.row == 2) {
        
        self.placeHolderText.hidden = YES;
    }
        
}



#pragma mark - 使用第三方框架添加多张图片

- (IBAction)clickSelectPhotoButton
{
    //从沙盒中取图片
    NSMutableArray *assets = [NSMutableArray array];
    NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"images"];
    NSLog(@"%@", imagePath);
    NSArray *localIdentifieArray = [NSKeyedUnarchiver unarchiveObjectWithFile:imagePath];
    
    PHFetchResult *phFetchResult = [PHAsset fetchAssetsWithLocalIdentifiers:localIdentifieArray options: nil];
    [phFetchResult enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx,BOOL *_Nonnull stop) {
        [assets addObject: obj];
    }];

    
    HMImagePickerController *picker = [[HMImagePickerController alloc] initWithSelectedAssets:self.selectedAssets];
    // 设置图像选择代理
    picker.pickerDelegate = self;
    // 设置目标图片尺寸
    picker.targetSize = CGSizeMake(600, 600);
    // 设置最大选择照片数量
    picker.maxPickerCount = 3;
    
    [self presentViewController:picker animated:YES completion:nil];

}


- (void)imagePickerController:(HMImagePickerController *)picker didFinishSelectedImages:(NSArray<UIImage *> *)images selectedAssets:(NSArray<PHAsset *> *)selectedAssets
{
    // 记录图像，方便在 CollectionView 显示
    self.images = images.mutableCopy;
    
    // 记录选中资源集合，方便再次选择照片定位
    self.selectedAssets = selectedAssets;
    
    //获取图片存储路径
    NSString *imagePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"images"];
    NSLog(@"%@", imagePath);
    //创建可变数组存储本地标识
    NSMutableArray *localIdentifierArr = [NSMutableArray  array];
    for (PHAsset *phAsset  in  _selectedAssets) {
        [localIdentifierArr  addObject: phAsset.localIdentifier ];
    }
    
    //根据图片的路径把本地标识归档
    [NSKeyedArchiver archiveRootObject:localIdentifierArr toFile:imagePath];
    
    //刷新界面
    [self.tableView reloadData];
    
    //让当前控制器自己消失
    [self dismissViewControllerAnimated:YES completion:nil];


}









@end
